package com.runen.infinitemovement.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.floatwindow.FloatWindowManager;
import com.runen.rxnetlibrary.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class SpecialPrivilegesActivity extends BaseActivity {
    @BindView(R.id.tv_xfc)
    TextView tv_xfc;
    @BindView(R.id.tv_dcyh)
    TextView tv_dcyh;
    @BindView(R.id.tv_htbhxtsz)
    TextView tv_htbhxtsz;
    @BindView(R.id.tv_fsmxtsz)
    TextView tv_fsmxtsz;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_jiaocheng)
    TextView tv_jiaocheng;
    @BindView(R.id.top_tv_right)
    TextView top_tv_right;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_special_privileges;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("运动权限设置");
        String str = "不会设置？<font color='#df2526'>点我看教程</font>";
        tv_jiaocheng.setText(Html.fromHtml(str));
    }

    @OnClick({R.id.top_btn_left, R.id.tv_xfc, R.id.tv_dcyh, R.id.tv_htbhxtsz, R.id.tv_fsmxtsz, R.id.tv_jiaocheng,
            R.id.top_tv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.tv_xfc:
                jumpToFloatPrivilege();
                break;
            case R.id.tv_dcyh:
                jumpToBatteryOptimization();
                break;
            case R.id.tv_htbhxtsz:
                backGroundSaveSystemSet();
                break;
            case R.id.tv_fsmxtsz:
                theSleepSystemSet();
                break;
            case R.id.tv_jiaocheng:
                Intent intent = new Intent();
                intent.setClass(SpecialPrivilegesActivity.this, WebActivity.class);
                String str = Build.MANUFACTURER.toLowerCase();
                intent.putExtra("LINK_URL", String.format(Constant.H5_SPORT_PERMISSION_JIAOCHENG, str));
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //悬浮窗
        boolean floatWindow = FloatWindowManager.getInstance().checkPermission(this);
        if (floatWindow) {
            tv_xfc.setText("已开启悬浮窗权限");
        } else
            tv_xfc.setText("开启悬浮窗权限");
        //电池优化
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean hasIgnored = false;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(getPackageName());
            if (!hasIgnored) {
                tv_dcyh.setText("已开启电池优化，点击关闭");
            } else {
                tv_dcyh.setText("已忽略电池优化");
            }
        }
    }

    /**
     * 跳转到悬浮窗权限
     */
    public void jumpToFloatPrivilege() {
        FloatWindowManager.getInstance().applyOrShowFloatWindow(this);
    }

    /**
     * 电池优化
     */
    public void jumpToBatteryOptimization() {
        ignoreBatteryOptimization();
    }

    /**
     * 后台保护系统设置
     */
    public void backGroundSaveSystemSet() {
        jumpStartInterface(this);
    }

    /**
     * 防睡眠
     */
    public void theSleepSystemSet() {
        jumpInterface(this);
    }

    /**
     * 忽略电池优化
     */
    private void ignoreBatteryOptimization() {
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean hasIgnored = false;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(getPackageName());
            //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
            if (!hasIgnored) {
                //未加入电池优化的白名单 则弹出系统弹窗供用户选择(这个弹窗也是一个页面)
                Intent intent = new Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            } else {
//                //已加入电池优化的白名单 则进入系统电池优化页面
//                Intent powerUsageIntent = new Intent(ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
//                ResolveInfo resolveInfo = activity.getPackageManager().resolveActivity(powerUsageIntent, 0);
//                //判断系统是否有这个页面
//                if (resolveInfo != null) {
//                    startActivity(powerUsageIntent);
//                }
                ToastUtils.showShort("已忽略电池优化");
            }
        }
    }

    //获取手机类型
    private static String getMobileType() {
        String PHONE_NAME = null;
        if (Build.BRAND != null) {
            PHONE_NAME = Build.BRAND.toLowerCase();
        }
        return PHONE_NAME;
    }

    //跳转至授权页面
    public void jumpStartInterface(Context context) {
        Intent intent = new Intent();
        try {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.e("HLQ_Struggle", "******************当前手机型号为：" + getMobileType());
            ComponentName componentName = null;
            if (getMobileType().equals("xiaomi")) { // 红米Note4测试通过
                componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
            } else if (getMobileType().equals("letv")) { // 乐视2测试通过
                intent.setAction("com.letv.android.permissionautoboot");
            } else if (getMobileType().equals("samsung")) { // 三星Note5测试通过
                componentName = ComponentName.unflattenFromString("com.samsung.android.sm/.app.dashboard.SmartManagerDashBoardActivity");
            } else if (getMobileType().equals("huawei")) { // 华为测试通过
                componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/.mainscreen.MainScreenActivity");//跳自启动管理
            } else if (getMobileType().equals("vivo")) { // VIVO测试通过
                componentName = ComponentName.unflattenFromString("com.iqoo.secure/.safeguard.PurviewTabActivity");
            } else if (getMobileType().equals("meizu")) { //万恶的魅族
                componentName = ComponentName.unflattenFromString("com.meizu.safe/.permission.SmartBGActivity");//跳转到后台管理页面
            } else if (getMobileType().equals("oppo")) { // OPPO R8205测试通过
                componentName = ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity");
            } else if (getMobileType().equals("ulong")) { // 360手机 未测试
                componentName = new ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity");
            } else {
                // 将用户引导到系统设置页面
                if (Build.VERSION.SDK_INT >= 9) {
                    Log.e("HLQ_Struggle", "APPLICATION_DETAILS_SETTINGS");
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
                }
            }
            intent.setComponent(componentName);
            context.startActivity(intent);
        } catch (Exception e) {//抛出异常就直接打开设置页面
            Log.e("HLQ_Struggle", e.getLocalizedMessage());
            intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }
    }

    //跳转至授权页面
    public void jumpInterface(Context context) {
        Intent intent = new Intent();
        try {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.e("HLQ_Struggle", "******************当前手机型号为：" + getMobileType());
            ComponentName componentName = null;
            if (getMobileType().equals("xiaomi")) {
                intent = jumpToMIUIAppDetail(context);
//                jumpToMIUIBackgroundLimit(context);
            } else if (getMobileType().equals("letv")) { // 乐视2测试通过
            } else if (getMobileType().equals("samsung")) { // 三星Note5测试通过
            } else if (getMobileType().equals("huawei")) { // 华为测试通过
                jumpToHUAWEIBackGroudLimit(context);
                return;
            } else if (getMobileType().equals("vivo")) { // VIVO测试通过
            } else if (getMobileType().equals("meizu")) { //万恶的魅族
            } else if (getMobileType().equals("oppo")) { // OPPO R8205测试通过
            } else if (getMobileType().equals("ulong")) { // 360手机 未测试
            } else {
                if (Build.VERSION.SDK_INT >= 9) {
                    Log.e("HLQ_Struggle", "APPLICATION_DETAILS_SETTINGS");
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
                }
            }
            if (componentName != null)
                intent.setComponent(componentName);
            context.startActivity(intent);
        } catch (Exception e) {//抛出异常就直接打开设置页面
            intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }
    }

    private void jumpToHUAWEIBackGroudLimit(Context context) {
        try {
            Intent localIntent = new Intent();
            localIntent.setComponent(ComponentName.unflattenFromString("com.huawei.systemmanager/.power.ui.HwPowerManagerActivity"));
            localIntent.putExtra("package_name", context.getPackageName());
            localIntent.putExtra("package_label", context.getString(R.string.app_name));
            localIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            context.startActivity(localIntent);
        } catch (Exception e) {
            try {
                Intent localIntent = new Intent();
                localIntent.setComponent(ComponentName.unflattenFromString("com.huawei.systemmanager/.mainscreen.MainScreenActivity"));
                localIntent.putExtra("package_name", context.getPackageName());
                localIntent.putExtra("package_label", context.getString(R.string.app_name));
                localIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                Intent localIntent = new Intent();
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
                context.startActivity(localIntent);
            }
        }
    }

    /**
     * 跳转到 app 应用详情
     *
     * @param context
     * @return
     */
    private Intent jumpToMIUIAppDetail(Context context) {
        Intent localIntent = new Intent();
        localIntent.setComponent(ComponentName.unflattenFromString("com.miui.securitycenter/com.miui.appmanager.ApplicationsDetailsActivity"));
        localIntent.putExtra("package_name", context.getPackageName());
        localIntent.putExtra("package_label", context.getString(R.string.app_name));
        localIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return localIntent;
    }

    /**
     * 跳转到小米 权限管理页面
     *
     * @param context
     */
    private void jumpToMIUIPermission(Context context) {
        try { // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (Exception e) {
            try { // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", context.getPackageName());
                context.startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                context.startActivity(getAppDetailSettingIntent(context));
            }
        }
    }

    /**
     * 跳转到小米 后台限制
     *
     * @param context
     */
    private void jumpToMIUIBackgroundLimit(Context context) {
        Intent localIntent = new Intent();
        localIntent.setComponent(new ComponentName("com.miui.powerkeeper",
                "com.miui.powerkeeper.ui.HiddenAppsConfigActivity"));
        localIntent.putExtra("package_name", context.getPackageName());
        localIntent.putExtra("package_label", context.getString(R.string.app_name));
        startActivity(localIntent);
    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     */
    private Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));

        return localIntent;
    }
}
